<template>
  <div class="mb-[20px] p-[20px] bg-[#dbdbdb]">
    <Button @click="selectDriver()">{{
      props.fromType === 'schedule' ? '司机调度' : '司机变更'
    }}</Button>
    <Form
      class="flex flex-wrap"
      ref="formRef"
      :label-col="{ style: { width: '150px' } }"
      :model="formState"
      :rules="rules"
    >
      <FormItem class="w-[33%]" label="司机姓名" name="driverName">
        <Input class="w-[100%]" v-model:value="formState.driverName" />
      </FormItem>

      <FormItem class="w-[33%]" label="电话" name="driverPhone">
        <Input class="w-[100%]" v-model:value="formState.driverPhone" />
      </FormItem>

      <FormItem class="w-[33%]" label="车牌号" name="vehicleNo">
        <Input class="w-[100%]" v-model:value="formState.vehicleNo" />
      </FormItem>

      <FormItem class="w-[33%]" label="司机身份证" name="driverIdCard">
        <Input class="w-[100%]" v-model:value="formState.driverIdCard" />
      </FormItem>

      <FormItem class="w-[33%]" label="车辆类型" name="vehicleModel">
        <Select
          style="width: 100%"
          v-model:value="formState.vehicleModel"
          placeholder="请选择车辆类型"
        >
          <SelectOption
            v-for="(key, value) in vehicleOptions"
            :key="key"
            :value="value"
            :label="key"
            >{{ key }}</SelectOption
          >
        </Select>
      </FormItem>
    </Form>
  </div>

  <TableModal
    v-bind="$attrs"
    :title="'司机列表'"
    @register="registerDriver"
    @success="handleDriverSuccess"
    :tableType="'radio'"
    :code="'eslogis_warehouse'"
    :tableColumn="tableColumnsDriver"
    :apiTableList="apiTableList"
    @visible-change="visibleChange"
  />
</template>
<script lang="ts" setup>
  import { ref, toRaw, computed, defineEmits, defineProps } from 'vue';
  import { Form, FormItem, Input, Select, SelectOption, message, Button } from 'ant-design-vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import { postSchedule, postScheduleUpdate } from '@/api/waybillManagement/index';
  import { VehicleModel } from '@/enums/comEnum';
  import TableModal from './TableModal.vue';
  import { useModal } from '@/components/Modal';
  import { getDriverInfo } from '@/api/eslogis-tps/index';

  const apiTableList = {
    getData: getDriverInfo,
  };

  const emit = defineEmits(['onSuccess', 'onFailed']);

  const props = defineProps({
    // queryParams: { type: Object },
    fromType: { type: String },
  });

  let formState: any = ref({});

  const formRef = ref();

  const vehicleOptions = computed(() => {
    const options = {};
    for (const [key, value] of Object.entries(VehicleModel)) {
      if (!isNaN(Number(key))) {
        options[key] = value;
      }
    }
    return options;
  });

  const rules: Record<string, Rule[]> = {
    driverName: [{ required: true, message: '请输入司机姓名', trigger: 'blur', type: 'string' }],
    driverPhone: [{ required: true, message: '请输入联系方式', trigger: 'blur', type: 'string' }],
    vehicleNo: [{ required: true, message: '请输入车牌号', trigger: 'blur', type: 'string' }],
    driverIdCard: [
      { required: true, message: '请输入司机身份证', trigger: 'blur', type: 'string' },
    ],
    vehicleModel: [{ required: true, message: '请选择车辆类型', trigger: 'change' }],
  };

  const initFormState = (queryParams) => {
    formState.value = {
      ...queryParams.value,
    };
    console.log('🚀 ~ initFormState ~ queryParams.value:', queryParams.value);
  };

  const [registerDriver, { openModal: openModalDriver }] = useModal();

  const tableColumnsDriver = [
    {
      title: '司机姓名',
      dataIndex: 'name',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '车牌号',
      dataIndex: 'licensePlate',
    },
    {
      title: '身份证',
      dataIndex: 'idNumber',
    },
    {
      title: '车辆类型',
      dataIndex: 'model',
    },
  ];

  function selectDriver() {
    openModalDriver(true); // 让弹窗弹出
  }

  function visibleChange(visible: boolean) {
    console.log('visible:boolean', visible);
  }

  // 选择仓库地址后回显
  function handleDriverSuccess(val) {
    const newTemp = val[0];
    formState.value.driverName = newTemp.name;
    formState.value.driverPhone = newTemp.mobile;
    formState.value.vehicleNo = newTemp.licensePlate;
    formState.value.driverIdCard = newTemp.idNumber;
    formState.value.vehicleModel = newTemp.model;
  }

  const Commit = async () => {
    console.log('values', formState, toRaw(formState));
    formRef.value
      .validate()
      .then(async () => {
        try {
          if (props.fromType === 'schedule') {
            await postSchedule(formState.value);
          } else {
            await postScheduleUpdate(formState.value);
          }

          message.success('处理成功');
          formState.value.queryParams = {};
          emit('onSuccess');
        } catch (error) {
          emit('onFailed');
        }
      })
      .catch((error) => {
        console.log('error', error);

        emit('onFailed');
      });
  };

  defineExpose({
    initFormState,
    Commit,
  });
</script>
